package ch10_IO流与文件.其他类;

import java.io.*;
import java.util.Date;

/**
 * @author 挚爱之夕
 * @date 2021/8/28 - 08 - 28 - 7:01
 * @Description: ch10.其他类
 * @Version: 1.0
 */
public class ConsoleDemo {
    public static void main(String[] args) throws IOException {
        Console c = System.console();   //得到控制台对象
        if(c == null){
            System.out.println("控制台不存在，请在命令行窗口启动程序！");
            System.exit(0);
        }
        //模拟用户登录
        String name = null,psw = null;
        name = c.readLine("账号：");//等待输入一行字符串
        psw = String.valueOf(c.readPassword("密码："));//输入密码
        if("admin".equalsIgnoreCase(name.trim())&&"admin".equals(psw)){//登录成功
            c.printf("%1$s 于 %2$tY-&2$tm-%2$td %2$tH:%2$tM:%2$tS 登录，欢迎！",name,new Date());
        }else {
            c.printf("账号或密码错误，程序退出！");
            System.exit(0);
        }

        //执行用户输入的命令并捕获输出
        String command = null;
        Process process =  null;
        String line = null;
        while(true){
            c.printf("\n>>");
            command = c.readLine();
            if("exit".equalsIgnoreCase(command)){
                c.printf("%1$s 于 %2$tY-&2$tm-%2$td %2$tH:%2$tM:%2$tS 退出，再见！",name,new Date());
                System.exit(0);
            }
            //通过操作系统执行输入的命令
            process = Runtime.getRuntime().exec("cmd / c"+command);
            //获得进程的输入流并包装（当执行的命令有输出信息时，将写到此输入流）
            try(InputStream is = process.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr)){
                while((line = br.readLine())!=null){    //读入一行信息
                    c.printf("%s\n",line);  //写入控制台
                }
            }
        }
    }
}
